package exercise.jslide.jslide.view.tools;

import exercise.jslide.jslide.app.AppContext;
import exercise.jslide.jslide.command.AddTextCommand;
import exercise.jslide.jslide.model.text.TextBox;
import exercise.jslide.jslide.view.EditorView;
import javafx.scene.Cursor;

//一些文本工具，目前的想法是会和textbox联用
public class TextTool implements Tool {
    private AppContext appContext;
    private EditorView editorView;
    private TextBox currentText;
    private double startX, startY;

    public TextTool(EditorView editorView) {
        this.appContext = AppContext.getInstance();
        this.editorView = editorView;
    }

    @Override
    public void activate() {
        editorView.setCursor(Cursor.CROSSHAIR);
    }

    @Override
    public void deactivate() {
        editorView.setCursor(Cursor.DEFAULT);
//        if(currentText!=null&&currentText.isEditing())
//        {
//            currentText.endEditing();
//        }
        currentText = null;
    }

    //鼠标的单击事件似乎需要加入分支，单击照常，双击进入分支？
    @Override
    public void handleMousePressed(double x, double y) {
        currentText = new TextBox();
        startX = x;
        startY = y;
        currentText.setX(startX);
        currentText.setY(startY);
        currentText.setWidth(100);
        currentText.setHeight(50);
//        editorView.getChildren().add(currentText);
        appContext.getCurrentPresentation()
                .getCurrentSlide()
                .addElement(currentText);

    }

    @Override
    public void handleMouseDragged(double x, double y) {




        if (currentText != null) {
            // 计算宽度和高度
            currentText.setWidth(Math.abs(x - startX));
            currentText.setHeight(Math.abs(y - startY));
            //确保文本框的绘制从左上角开始
            double newX = x<startX?x:startX;
            double newY = y<startY?y:startY;
            currentText.setX(newX);
            currentText.setY(newY);


            appContext.getMainView().updateView();


        }
    }

    @Override
    public void handleMouseReleased(double x, double y) {
        if (currentText != null) {
            // 添加撤销/重做命令
            AddTextCommand addTextCommand = new AddTextCommand(
                    appContext.getCurrentPresentation(),
                    currentText
            );
            appContext.getUndoManager().executeCommand(addTextCommand);

            // 切换到选择工具
            editorView.setCurrentTool(null);

            currentText = null;
        }
    }

}